<template>
  <div class="client-management-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2 class="page-title">客户管理</h2>
      <el-button 
        type="primary" 
        size="small" 
        @click="refreshData"
        :loading="loading"
        :icon="Refresh"
      >
        刷新
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索客户代码或店名"
          @input="onSearch"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <div class="filter-section">
        <div class="filter-row">
          <el-select 
            v-model="filterMarketType" 
            placeholder="市场类型"
            clearable
            @change="onFilterChange"
          >
            <el-option label="城网" value="城网" />
            <el-option label="农网" value="农网" />
          </el-select>
          
          <el-select 
            v-model="filterTerminalType" 
            placeholder="终端类型"
            clearable
            @change="onFilterChange"
          >
            <el-option label="普通终端" value="普通终端" />
            <el-option label="一般现代终端" value="一般现代终端" />
            <el-option label="加盟终端" value="加盟终端" />
            <el-option label="直营终端" value="直营终端" />
          </el-select>
        </div>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="stats-card">
      <div class="stats-row">
        <div class="stat-item">
          <div class="stat-number">{{ filteredClients.length }}</div>
          <div class="stat-label">当前显示</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ allClients.length }}</div>
          <div class="stat-label">负责客户</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ marketTypeStats.城网 || 0 }}</div>
          <div class="stat-label">城网</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ marketTypeStats.农网 || 0 }}</div>
          <div class="stat-label">农网</div>
        </div>
      </div>
    </div>

    <!-- 客户列表 -->
    <div class="clients-container">
      <div class="clients-list" v-if="filteredClients.length > 0">
        <div 
          v-for="client in filteredClients" 
          :key="client.id"
          class="client-card"
          @click="editClient(client)"
        >
          <div class="client-header">
            <div class="client-info">
              <h4 class="client-name">{{ client.clientName }}</h4>
              <span class="client-code">{{ client.clientCode }}</span>
            </div>
            <div class="client-actions">
              <el-icon class="edit-icon"><Edit /></el-icon>
            </div>
          </div>

          <div class="client-details">
            <div class="detail-row">
              <el-tag size="small">{{ client.marketType }}</el-tag>
              <el-tag size="small" type="info">{{ client.terminalType }}</el-tag>
            </div>
            
            <div class="client-stats" v-if="client._count">
              <span class="stat-badge">
                服务项目: {{ client._count.serviceAssignments || 0 }}
              </span>
              <span class="stat-badge">
                工作记录: {{ client._count.workLogs || 0 }}
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div class="empty-state" v-else-if="!loading">
        <el-empty :description="getEmptyDescription()" :image-size="100">
          <el-button type="primary" @click="clearFilters" v-if="hasActiveFilters">
            清除筛选条件
          </el-button>
        </el-empty>
      </div>

      <!-- 加载状态 -->
      <div class="loading-state" v-if="loading">
        <el-skeleton :rows="5" animated />
      </div>
    </div>

    <!-- 分页加载 -->
    <div class="load-more" v-if="hasMore && !loading">
      <el-button 
        type="primary" 
        @click="loadMore"
        :loading="loadingMore"
        block
      >
        加载更多
      </el-button>
    </div>

    <!-- 底部安全区域 -->
    <div class="safe-area-bottom"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Refresh, 
  Search, 
  Edit
} from '@element-plus/icons-vue'
import { trpc } from '@/utils/trpc'
import { AuthUtils } from '@/utils/auth'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const loadingMore = ref(false)
const searchKeyword = ref('')
const filterMarketType = ref('')
const filterTerminalType = ref('')
const allClients = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const hasMore = ref(true)

// 防抖搜索
let searchTimeout: NodeJS.Timeout | null = null

// 计算属性
const filteredClients = computed(() => {
  let clients = allClients.value

  // 按关键词搜索
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.trim().toLowerCase()
    clients = clients.filter((client: any) => 
      client.clientName.toLowerCase().includes(keyword) ||
      client.clientCode.toLowerCase().includes(keyword)
    )
  }

  // 按市场类型筛选
  if (filterMarketType.value) {
    clients = clients.filter((client: any) => 
      client.marketType === filterMarketType.value
    )
  }

  // 按终端类型筛选
  if (filterTerminalType.value) {
    clients = clients.filter((client: any) => 
      client.terminalType === filterTerminalType.value
    )
  }

  return clients
})

const marketTypeStats = computed(() => {
  const stats = { 城网: 0, 农网: 0 }
  allClients.value.forEach((client: any) => {
    if (stats[client.marketType] !== undefined) {
      stats[client.marketType]++
    }
  })
  return stats
})

const hasActiveFilters = computed(() => {
  return searchKeyword.value.trim() || filterMarketType.value || filterTerminalType.value
})

// 方法
const loadClients = async (page = 1, append = false) => {
  try {
    if (!append) {
      loading.value = true
    } else {
      loadingMore.value = true
    }
    
    const managerId = getCurrentManagerId()
    if (!managerId) {
      ElMessage.error('请先登录')
      return
    }

    const result = await trpc.manager.clients.query({
      managerId,
      page,
      pageSize: pageSize.value
    })

    if (result.success) {
      const newClients = result.data.data || []
      
      if (append) {
        allClients.value = [...allClients.value, ...newClients]
      } else {
        allClients.value = newClients
      }
      
      // 检查是否还有更多数据
      const totalPages = result.data.pagination?.totalPages || 1
      hasMore.value = page < totalPages
      currentPage.value = page
    } else {
      ElMessage.error('加载客户列表失败')
    }
  } catch (error) {
    console.error('加载客户列表失败:', error)
    ElMessage.error('加载客户列表失败')
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

const refreshData = () => {
  currentPage.value = 1
  hasMore.value = true
  loadClients(1, false)
}

const loadMore = () => {
  if (hasMore.value && !loadingMore.value) {
    loadClients(currentPage.value + 1, true)
  }
}

const onSearch = () => {
  // 清除之前的定时器
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  
  // 设置新的防抖定时器
  searchTimeout = setTimeout(() => {
    // 搜索时不需要重新加载数据，因为是客户端筛选
  }, 300)
}

const onFilterChange = () => {
  // 筛选变化时也不需要重新加载，客户端筛选即可
}

const clearFilters = () => {
  searchKeyword.value = ''
  filterMarketType.value = ''
  filterTerminalType.value = ''
}

const editClient = (client: any) => {
  router.push({
    name: 'ClientEdit',
    params: { clientId: client.id }
  })
}

const getEmptyDescription = () => {
  if (hasActiveFilters.value) {
    return '没有找到符合条件的客户'
  }
  return '您暂时没有负责的客户'
}

const getCurrentManagerId = () => {
  const user = AuthUtils.getUser<any>()
  return user?.id || null
}

// 生命周期
onMounted(() => {
  loadClients()
})
</script>

<style scoped>
.client-management-page {
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: white;
  border-bottom: 1px solid #ebeef5;
}

.page-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.search-section {
  background: white;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.search-bar {
  margin-bottom: 16px;
}

.filter-section {
  width: 100%;
}

.filter-row {
  display: flex;
  gap: 12px;
}

.filter-row .el-select {
  flex: 1;
}

.stats-card {
  margin: 12px;
  background: white;
  border-radius: 12px;
  padding: 16px;
}

.stats-row {
  display: flex;
  justify-content: space-around;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 20px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

.clients-container {
  padding: 0 12px;
}

.clients-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.client-card {
  background: white;
  border-radius: 12px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid transparent;
}

.client-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.15);
}

.client-card:active {
  transform: scale(0.98);
}

.client-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 12px;
}

.client-info h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.client-code {
  font-size: 12px;
  color: #909399;
}

.client-actions {
  display: flex;
  align-items: center;
}

.edit-icon {
  color: #409eff;
  font-size: 18px;
}

.client-details {
  space-y: 8px;
}

.detail-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.client-stats {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.stat-badge {
  font-size: 12px;
  color: #606266;
  background: #f5f7fa;
  padding: 2px 8px;
  border-radius: 10px;
}

.empty-state, .loading-state {
  padding: 40px 20px;
  background: white;
  margin: 12px;
  border-radius: 12px;
}

.load-more {
  padding: 16px 12px;
}

.safe-area-bottom {
  height: 20px;
}

:deep(.el-input__inner) {
  border-radius: 20px;
}

:deep(.el-select .el-input__inner) {
  border-radius: 8px;
}

:deep(.el-skeleton__item) {
  border-radius: 8px;
}
</style>